package com.example.udpNet;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.*;

/**
 * @Author 郅占伟
 * @ClassName TestUDP
 * @Description TODO
 * @Date 2024年05月15日
 * @Version: 1.0
 */
public class TestUDP {
    @Test
    public void getData() throws IOException {
        // 创建接收端Socket，指定 IP 地址
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        DatagramSocket datagramSocket = new DatagramSocket(12306, inetAddress);

        // 创建数据包(接受容器)
        byte[] bytes = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
        System.out.println("接收数据服务已打开，等待接收数据");

        // 调用接收方法
        datagramSocket.receive(datagramPacket);

        // 解析数据包，把数据显示在控制台
        InetAddress address = datagramPacket.getAddress();

        String hostAddress = address.getHostAddress();
        byte[] data = datagramPacket.getData();
        int length = datagramPacket.getLength();

        String s = new String(data, 0, length);
        System.out.println(hostAddress + "****" + s);

        System.out.println("接收数据完毕，接收数据服务关闭");

        // 释放资源
        datagramSocket.close();
    }

    @Test
    public void sendData() throws IOException {
        // 创建发送端 Socket 服务对象
        DatagramSocket datagramSocket = new DatagramSocket();

        // 创建数据，并把数据打包
        String data = "hello world";
        byte[] bytes = data.getBytes();
        int length = bytes.length;

        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        int port = 12306;

        DatagramPacket datagramPacket = new DatagramPacket(bytes, length, inetAddress, port);
        System.out.println("发送数据服务已打开");
        System.out.println("发送数据是：" + data);

        // 发送数据
        datagramSocket.send(datagramPacket);
        System.out.println("发送完毕，关闭服务");

        // 释放资源
        datagramSocket.close();
    }
}
